package com.itheima.health.controller;

import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.util.ValidateCodeUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * 验证码Controller
 */
@RestController
@RequestMapping("/mobile/validateCode")
@Slf4j
@Api(tags = "手机端验证码接口")
public class MobileValidateCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/send")
    //接收前端传输的参数,注意！！！前端请求后面的？不得使用实体类接受
    public Result send(String type,String telephone){
        //获取到手机号
//        String telephone = quickLogon.getTelephone();
        //调用后端生成验证码的程序
        String usercode = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("生成了验证码,验证码为:{}",usercode);

        //调用 阿里云接口  api
        // SMSUtils.sendMessage("阿里云测试","模板SMS_154950909","telephone","验证码");

        //将验证码和手机号存储到session域中，保证可以从此次会话中拿到这些数据
//        httpSession.setAttribute(telephone,code);  可以将验证码放入Redis中设置过期时间减少服务器压力
        //以下代码将拿到的手机号码和生成的验证码放入Redis中并设置过期时间为两分钟
        String key = RedisConst.VALIDATE_CODE_PREFIX+type+"_"+telephone;
        redisTemplate.opsForValue().set(key,usercode,2,TimeUnit.MINUTES);
        return new Result(true,"验证码发送成功");
    }


}
